import { queryArticleDetail, addArticle, updateArticle } from "@/api/content/article";
import { uploadFile } from "@/api/file";
import { Article } from "@/types/content/article";
import { deleteFileInf } from "@/utils/deleteFileInf";
import { message, UploadFile } from "antd";
import { useForm } from "antd/es/form/Form";
import { useState, useCallback, useEffect } from "react";
import { useSearchParams } from "react-router-dom";

interface ImgAddReturn {
    url: string;
    title: string;
}
export const useWriting = () => {
    const [searchParams] = useSearchParams();
    const id = searchParams.get("id") || "";
    const [messageApi] = message.useMessage();
    const [open, setOpen] = useState(false);
    const [form] = useForm();
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    const [ruleForm, setRuleForm] = useState<Article.Row>({
        id: "",
        // 文章标题
        title: "[无标题]",
        // 可否评论
        isComment: "0",
        // 是否置顶
        isTop: "1",
        // 文章摘要
        summary: "",
        // 标签
        tags: [],
        // 缩略图
        thumbnail: "",
        // 分类
        categoryId: "",
        codeTheme: "nnfx-light",
        content: "",
        status: "1",
    });
    /**
 * 上传图片
 */
    const imgAdd = async (files: File[]): Promise<ImgAddReturn[]> => {
        try {
            const formData = new FormData();
            formData.append("file", files[0]);
            const res = await uploadFile(formData);
            if (res.code === 200) {
                return [
                    {
                        title: "",
                        url: res.data,
                    },
                ];
            }
            return [];
        } catch (error) {
            console.log(error);
            return [];
        }
    };
    const getArticleDetail = useCallback(async () => {
   
        const res = await queryArticleDetail(id);
        if (res.code === 200 && res.data) {
            const obj = {
                ...res.data,
                tags: res.data.tagList
                    ? res.data.tagList.map((item) => item.tagId)
                    : [],
            };
            setRuleForm(obj);
            form.setFieldsValue(obj);
            if (res.data.thumbnail) {
                setFileList([
                    {
                        uid: "-1",
                        name: "",
                        status: "done",
                        url: res.data.thumbnail,
                    },
                ]);
            }
        }
    }, [form, id]);
    const addArticleInf = async (data: Article.Row) => {
        const res = await addArticle(data);

        if (res.code === 200) {
            messageApi.success("保存成功");
            setRuleForm({
                ...ruleForm,
                id: res.data || "",
            });
            setOpen(false)
        } else {
            messageApi.error(res.msg);
        }
    };
    /**
     * 更新文章
     */

    const updateArticleInf = async (data: Article.Row) => {
        const res = await updateArticle(data);
        if (res.code === 200) {
            messageApi.success("已修改");
            setOpen(false)
            getArticleDetail();
        } else {
            messageApi.error("已删除");
        }
    };
    const saveOrEdit = (data: Article.Row, isPublis?: boolean) => {
        const thumbnail = fileList[0] && fileList[0].url ? fileList[0].url : "";
        const params = {
            ...data,
            thumbnail,
            content:ruleForm.content,
            title:ruleForm.title,
            id:ruleForm.id
        };
        if (isPublis) {
            params.status = "0";
        }else{
            params.status = '1'
        }
        if (params.id) {
            updateArticleInf(params);
        } else {
            addArticleInf(params);
        }
    };
    const onClose = () => {
        setOpen(false);
    };
    const uploadFileInf = async (file: File | string | Blob) => {
        if (typeof file === "string") return;
        const formData = new FormData();
        formData.append("file", file);
        try {
            const res = await uploadFile(formData);
            const url = fileList[0] && fileList[0].url ? fileList[0].url : "";
            if (url) {
                deleteFileInf(url);
            }

            if (res.data) {
                setFileList([
                    {
                        uid: "-1",
                        name: "",
                        status: "done",
                        url: res.data,
                    },
                ]);
            }
        } catch (error) {
            console.error(error);
        }
    };
    const onSave = () => {
        if (ruleForm.status === "1") {
            saveOrEdit(ruleForm);
        } else {
            setOpen(true);
        }
    };
    const openPublish = () => {
        setOpen(true);
    };
    useEffect(() => {
        if (!id) {
            form.setFieldsValue(ruleForm);
            return;
        }
        getArticleDetail();
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [form, getArticleDetail, id]);
    return {
        ruleForm,
        setRuleForm,
        onSave,
        openPublish,
        imgAdd,
        onClose,
        form,
        open,
        saveOrEdit,
        fileList,
        uploadFileInf,
        setFileList,
        setOpen
    }

}